#!/usr/bin/env /usr/local/python3
# -*- coding: utf-8 -*-

"""
python 操作RabbitMQ
"""

__author__ = 'hubert'

import pika
import time

# 127.0.0.1 175.6.15.136
host = '175.6.15.136'
port = 5672
# test beijing_dianxin_pake,choongqing_xinmeiti
userName = 'hebeiiptv_new'
# test tnBnEW4lJs596D , Tvup67;^R~}*Py
passWord = 'q\Yf|en>4rif+]'
# test_vhosts cms_host
virtualHost = 'cms_host'


# 生产者,采用默认exchange，为direct类型，通过指定队列名称(如:Python)的方式写入或获取消息
def producer():
    # 设置用户密码
    credentials = pika.PlainCredentials(userName, passWord)
    # 设置IP、端口、vhost信息
    connection = pika.BlockingConnection(pika.ConnectionParameters(host, port, virtualHost, credentials))
    # 创建频道
    channel = connection.channel()
    # channel.exchange_declare()
    # 声明消息队列，若队列不存在，则创建，durable=true 设置队列持久化
    channel.queue_declare(queue='Python', durable=True)

    """
    # 1.不指定exchange，表示采用默认exchange，
    # 2.默认的Exchange隐式绑定到每个队列，路由键等于队列名称。无法与默认交换机显式绑定或解除绑定。它也不能被删除。
    # 3.body是要插入的内容
    """
    length = 10
    # delivery_mode=2 消息持久化
    properties = pika.BasicProperties(delivery_mode=2)
    for index in range(length):
        body = 'Python' + str(index+1)
        pub = channel.basic_publish(exchange='', routing_key='Python', body=body, properties=properties)
        if pub:
            print('发送成功', str(index+1))
        else:
            print('发送失败', str(index+1))
    print("----发送消息完毕---")
    # 关闭链接
    connection.close()


# 定义一个回调函数来处理，这边的回调函数就是将信息打印出来。
def callback(channel, method, properties, body):
    print(" [x] Received %r" % body.decode('utf-8'))
    time.sleep(30)
    print('ok!')
    # 确认回执
    channel.basic_ack(delivery_tag=method.delivery_tag)


# 订阅模式，采用默认exchange，默认routingKey与queue相同
def customer():
    # 设置用户密码
    credentials = pika.PlainCredentials(userName, passWord)
    # 设置IP、端口、vhost信息
    connection = pika.BlockingConnection(pika.ConnectionParameters(host, port, virtualHost, credentials))
    # 创建频道
    channel = connection.channel()

    # durable=True 队列持久化
    channel.queue_declare(queue='Python', durable=True)
    # 告诉rabbitmq使用callback来接收信息,no_ack=False 关闭自动回执
    channel.basic_consume(callback, queue='Python', no_ack=False)
    print(' [*] Waiting for messages. To exit press CTRL+C')
    # 开始接收信息，并进入阻塞状态，队列里有信息才会调用callback进行处理。按ctrl+c退出。
    channel.start_consuming()


# basicget 轮询
def customer_get():
    # 设置用户密码
    credentials = pika.PlainCredentials(userName, passWord)
    # 设置IP、端口、vhost信息
    connection = pika.BlockingConnection(pika.ConnectionParameters(host, port, virtualHost, credentials))
    # 创建频道
    channel = connection.channel()

    # 返回多个值(3个值)，为list,测试队列为Python,beijing_dianxin_pake_assetInfo,choongqing_xinmeiti_assetInfo
    # 具体返回情况，可参阅basic_get源码
    response = channel.basic_get('hebei_liantong_iptv_assetInfo', no_ack=False)
    delivery_tag = 0
    # 判断是否为空
    if response[2] is None:
        print('队列无内容!', time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
    else:
        # b'Python1'表示bytes类型,response[0]为类对象，对于类对象，可直接通过类获取类属性(面向对象编程)
        print('MQ消息为:', response[2].decode('utf-8'))
        delivery_tag = response[0].delivery_tag
        print('当前时间：', time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
        print('剩余消息:', response[0].message_count)
        print('返回结果:', response[0].delivery_tag)

    # 若不执行反馈，MQ数据不会删除，永远只能取的队列第一条数据
    # channel.basic_ack(delivery_tag=delivery_tag)
    connection.close()


if __name__ == '__main__':
    # producer()
    customer_get()
    # customer()




